package com.example.springstudy.filter;

import com.example.springstudy.utils.RequestWrapper;
import lombok.SneakyThrows;
import org.apache.tomcat.jni.Time;
import org.springframework.boot.autoconfigure.security.SecurityProperties;

import javax.management.timer.Timer;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import com.example.springstudy.utils.ResponseWrapper;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhaoJunZhou
 * @Date 2020/10/23
 */
@WebFilter(filterName = "myFilter", urlPatterns = {"/*"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /***
     * 使用ResponseWrapper可以获取到HttpServletResponse中的body
     * 的内容，调用chain.doFilter(requestWrapper, responseWrapper);
     * 返回的话如果为：ResponseWrapper读取过getBytes()之后需要对此进行
     * 重新塞入而放回用HttpServletResponse没有读取过其中的值就不需要
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        byte[] bytes = null;
        byte[] bytes1 = {0x31,0x32};
       try {

           String uri = req.getRequestURI();
           System.out.println(String.format("==========url:%s", uri));
           ResponseWrapper responseWrapper = new ResponseWrapper(resp);
           RequestWrapper requestWrapper = new RequestWrapper(req);
           /**
            * 如果 doFilter和   bytes= responseWrapper.getBytes();
            * 顺序相反则会造成http长时间无法关闭的问题
            */
           chain.doFilter(requestWrapper, responseWrapper);

           bytes= responseWrapper.getBytes();

       }catch (Exception e){
           e.printStackTrace();
       }finally {
            resp.getOutputStream().write(bytes);
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
       }


        System.out.println("chain.doFilter(request,response)之后");
    }

    @Override
    public void destroy() {

    }
}
